package com.example.teaching_server.entity;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDateTime;

/**
 * 课程录制实体类
 */
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = "id")
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "course_recordings", indexes = {
        @Index(name = "idx_start_time", columnList = "startTime"),
        @Index(name = "idx_class_name", columnList = "className")
})
public class CourseRecording {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "thumbnail_url", nullable = false)
    @NotBlank(message = "缩略图URL不能为空")
    private String thumbnailUrl;

    @Column(nullable = false)
    @NotBlank(message = "标题不能为空")
    private String title;

    @Column(name = "start_time", nullable = false)
    @NotNull(message = "开始时间不能为空")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime startTime;

    @Column(name = "end_time", nullable = false)
    @NotNull(message = "结束时间不能为空")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime endTime;

    @Column(name = "class_name", nullable = false)
    @NotBlank(message = "班级名称不能为空")
    private String className;

    @Column(length = 2000)
    private String description;

    @Column(name = "video_url", nullable = false)
    @NotBlank(message = "视频URL不能为空")
    private String videoUrl;

    @CreationTimestamp
    @Column(name = "created_at", updatable = false)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createdAt;

    @UpdateTimestamp
    @Column(name = "updated_at")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updatedAt;

    @Transient
    public boolean isLiveRecording() {
        return startTime != null && endTime != null &&
                startTime.isAfter(LocalDateTime.now().minusDays(1));
    }

    @PrePersist
    @PreUpdate
    private void validateTimes() {
        if (endTime != null && startTime != null && endTime.isBefore(startTime)) {
            throw new IllegalArgumentException("结束时间不能早于开始时间");
        }
    }
}
